package com.zh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zh.entity.AuthTongdun;
import com.zh.entity.Business;
import com.zh.entity.QueryLog;
import com.zh.entity.User;
import com.zh.service.AuthTongdunService;
import com.zh.service.BusinessService;
import com.zh.service.QueryLogService;
import com.zh.util.IdcardValidator;
import com.zh.util.demo.PreloanQueryResponse;
import com.zh.util.demo.PreloanSubmitResponse;
import com.zh.util.dict.CodeMsg;
import com.zh.util.dict.Validator;
import com.zh.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Validated
public class AuthTongdunController extends BaseController {

    @Autowired
    private AuthTongdunService authTongdunService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private QueryLogService queryLogService;

    @PostMapping("/authIdentity")
    public Result authIdentity(User user,
            @NotNull(message = "姓名不能为空")
            @Pattern(regexp = Validator.REGEX_CHINESE_NAME, message = "姓名格式错误")
                    String name,
            @NotNull(message = "手机号不能为空")
            @Pattern(regexp = Validator.REGEX_MOBILE, message = "手机号格式错误")
                    String mobile,
            @NotNull(message = "身份证不能为空")
            @Pattern(regexp = Validator.REGEX_ID_CARD, message = "身份证格式错误")
                    String identity){

        IdcardValidator iv = new IdcardValidator();
        if (!iv.isValidatedAllIdcard(identity)) {
            return Result.failure(CodeMsg.IDENTITY_FORMAT_ERROR);
        }


        Business business = businessService.selectById(user.getBusinessId());

        if(business.getHasCount()<=0){
            return Result.failure(CodeMsg.AUTH_NOT_HAS_COUNT);
        }

        Map<String, Object> tps = new HashMap<String, Object>();
        tps.put("name", name);
        tps.put("mobile", mobile);
        tps.put("identity", identity);

        Map<String, Object> tdps = tongdunParams(tps);//组装好同盾的请求参数
        super.logger.debug("同盾申请请求值：" + JSONObject.toJSONString(tdps));
        PreloanSubmitResponse riskPreloanResponse = authTongdunService.getPreloanSubmitResponse(tdps);
        super.logger.debug("同盾申请返回值:" + riskPreloanResponse.toString());

        if (!riskPreloanResponse.getSuccess()) {
            super.logger.error("同盾申请返回值错误：" + riskPreloanResponse.toString());
            return Result.failure(CodeMsg.APPLY_TONGDUN_AUTH_FAILURE);
        }

        // 申请成功后，等待一定时间，可调用query接口查询结果。
        // 官方建议等待时间：5s，为了保证更高的成功值，设置成6.5s
        try {
            Thread.sleep(6500);
        } catch (Exception e) {

        }
        // query接口获取结果
        PreloanQueryResponse response = authTongdunService.getPreloanQueryResponse(riskPreloanResponse.getReport_id());

        if (!response.getSuccess()) {
            super.logger.error("6500   ---   同盾query结果失败:" + response.toString());
            return Result.failure(CodeMsg.APPLY_TONGDUN_AUTH_FAILURE);
        }

        //获取风险检查项
        JSONArray jsonArr = null;
        JSONObject json = null;
        super.logger.debug("=========================  同盾风险检查项结果 start   =============================");
        try {
            jsonArr = response.getRisk_items();
        }catch (JSONException e){
            super.logger.error("=================  同盾query风险检查项结果错误，结果为：" + response.getRisk_items() + "  ===============");
        }

        if(jsonArr != null){
            super.logger.debug(jsonArr.toJSONString());
        }else{
            super.logger.debug("=================  同盾query风险检查项结果错误，结果为：" + response.getRisk_items() + "  ===============");
        }
        super.logger.debug("=========================  同盾风险检查项结果 end   =============================");


        Date date = new Date();
        AuthTongdun at = new AuthTongdun();
        at.setAddressDetect(response.getAddress_detect().toJSONString());
        at.setCreateTime(date);
        at.setFinalDecision(response.getFinal_decision());
        at.setFinalScore(response.getFinal_score());
        at.setId(super.getNextId());
        at.setReportId(response.getReport_id());
        if(jsonArr != null){
            at.setRiskItems(response.getRisk_items().toJSONString());
        }else{
            at.setRiskItems("[]");
        }
        at.setStatus(1);
        at.setUserId(user.getId());
        at.setBusinessId(user.getBusinessId());


        business.setHasCount(business.getHasCount()-1);
        business.setAllQueryCount(business.getAllQueryCount()+1);

        QueryLog queryLog = new QueryLog();
        queryLog.setBusinessId(user.getBusinessId());
        queryLog.setCreateDate(date);
        queryLog.setCreateTime(date);
        queryLog.setId(super.getNextId());
        queryLog.setIdentity(identity);
        queryLog.setMobile(mobile);
        queryLog.setUserAccount(user.getId());
        queryLog.setName(name);
        queryLog.setTongdunId(at.getId());

        authTongdunService.authIdentity(at,business,queryLog);

        Map<String, Object> tongdunMap = new HashMap<String,Object>();

        Integer finalScore = at.getFinalScore();
        String riskItemsStr = at.getRiskItems();
        String addressDetectStr = at.getAddressDetect();
        //转换成JSON
        List<Object> riskItemsList = JSON.parseArray(riskItemsStr);
        JSONObject addressDetect = JSON.parseObject(addressDetectStr);

        //打包到MAP
        tongdunMap.put("createTime", at.getCreateTime());
        tongdunMap.put("finalScore", finalScore);
        tongdunMap.put("finalDecision", at.getFinalDecision());
        //身份信息
        tongdunMap.put("queryLog", queryLog);
        tongdunMap.put("riskItems", riskItemsList);
        tongdunMap.put("addressDetect", addressDetect);

        return Result.success(tongdunMap);
    }

    public static Map<String, Object> tongdunParams(Map<String, Object> map) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loan_amount", ""); // 申请借款金额
        params.put("loan_term", ""); // 申请借款期限
        params.put("loan_term_unit", ""); // 期限单位
        params.put("loan_date", ""); // 申请借款日期
        params.put("purpose", ""); // 借款用途
        params.put("apply_province", ""); // 进件省份
        params.put("apply_city", ""); // 进件城市
        params.put("apply_channel", ""); // 进件渠道
        params.put("name", map.get("name")); // 姓名
        params.put("id_number", map.get("identity")); // 身份证号
        params.put("mobile", map.get("mobile")); // 手机号
        params.put("card_number", ""); // 银行卡
        params.put("work_phone", ""); // 单位座机
        params.put("home_phone", ""); // 家庭座机
        params.put("qq", ""); // qq
        params.put("email", ""); // 电子邮箱
        params.put("diploma", ""); // 学历
        params.put("marriage", ""); // 婚姻
        params.put("house_property", ""); // 房产情况
        params.put("house_type", ""); // 房产类型
        params.put("registered_address", ""); // 户籍地址
        params.put("home_address", ""); // 家庭地址
        params.put("contact_address", ""); // 通讯地址
        params.put("career", ""); // 职业
        params.put("applyer_type", ""); // 申请人类别
        params.put("work_time", ""); // 工作时间
        params.put("company_name", ""); // 工作单位
        params.put("company_address", ""); // 单位地址
        params.put("company_industry", ""); // 公司行业
        params.put("company_type", ""); // 公司性质
        params.put("occupation", ""); // 职位
        params.put("annual_income", ""); // 年收入
        params.put("is_cross_loan", ""); // 三个月内是否跨平台申请借款
        params.put("cross_loan_count", ""); // 三个月内跨平台申请借款平台个数
        params.put("is_liability_loan", ""); // 三个月内是否跨平台借款负债
        params.put("liability_loan_count", ""); // 三个月内跨平台借款负债平台个数
        params.put("is_id_checked", ""); // 是否通过实名认证
        params.put("contact1_relation", ""); // 第一联系人社会关系
        params.put("concatc1_name", ""); // 第一联系人姓名
        params.put("contact1_id_number", ""); // 第一联系人身份证
        params.put("contact1_mobile", ""); // 第一联系人手机号
        params.put("contact1_addr", ""); // 第一联系人家庭地址
        params.put("contact1_com_name", ""); // 第一联系人工作单位
        params.put("contact1_com_addr", ""); // 第一联系人工作地址
        params.put("contact2_relation", "");
        params.put("contact2_name", "");
        params.put("contact2_id_number", "");
        params.put("contact2_mobile", "");
        params.put("contact2_addr", "");
        params.put("contact2_com_name", "");
        params.put("contact2_com_addr", "");
        params.put("contact3_relation", "");
        params.put("contact3_name", "");
        params.put("contact3_id_number", "");
        params.put("contact3_mobile", "");
        params.put("contact3_addr", "");
        params.put("contact3_com_name", "");
        params.put("contact3_com_addr", "");
        params.put("contact4_relation", "");
        params.put("contact4_name", "");
        params.put("contact4_id_number", "");
        params.put("contact4_mobile", "");
        params.put("contact4_addr", "");
        params.put("contact4_com_name", "");
        params.put("contact4_com_addr", "");
        params.put("contact5_relation", "");
        params.put("contact5_name", "");
        params.put("contact5_id_number", "");
        params.put("contact5_mobile", "");
        params.put("contact5_addr", "");
        params.put("contact5_com_name", "");
        params.put("contact5_com_addr", "");
        params.put("ip_address", ""); // IP地址
        params.put("token_id", ""); // token_id
        params.put("black_box", ""); // black_box
        return params;
    }

    @PostMapping("/tongdunDetail")
    public Result tongdunDetail(@NotNull(message = "id不能为空") String id){

        QueryLog ql = queryLogService.selectById(id);
        if(ql==null){
            return Result.failure(CodeMsg.AUTH_REPORT_NOT_EXIST);
        }

        AuthTongdun at = authTongdunService.selectById(ql.getTongdunId());
        if(at==null){
            return Result.failure(CodeMsg.AUTH_REPORT_NOT_EXIST);
        }

        Map<String, Object> tongdunMap = new HashMap<String,Object>();

        Integer finalScore = at.getFinalScore();
        String riskItemsStr = at.getRiskItems();
        String addressDetectStr = at.getAddressDetect();

        //转换成JSON
        List<Object> riskItemsList = JSON.parseArray(riskItemsStr);
        JSONObject addressDetect = JSON.parseObject(addressDetectStr);

        //打包到MAP
        tongdunMap.put("createTime", at.getCreateTime());
        tongdunMap.put("finalScore", finalScore);
        tongdunMap.put("finalDecision", at.getFinalDecision());
        //身份信息
        tongdunMap.put("queryLog", ql);
        tongdunMap.put("riskItems", riskItemsList);
        tongdunMap.put("addressDetect", addressDetect);

        return Result.success(tongdunMap);

    }

}
